;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.DeptSellOrderMonitor", [])
        .controller("DeptSellOrderMonitorCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "EventBus", "$filter", "UserContextService", "$stateParams", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, EventBus, $filter, UserContextService, $stateParams) {
            // isNewAudit:销售订单新增审核功能
            // JCBJ07（基础）
            //（履带吊）
            $scope.isNewAudit = $scope.isJCH || $scope.isLDD;

            $scope.activeFlag = [true, false, false, false, false, false];
            $scope.sourceFlag = null;
            $scope.datePickerFlag = [false, false];
            $scope.subTabFlag = [true, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.billNo = "";
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.pageInfoPurchase = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.condition = {};
            $scope.billCondition = {};
            $scope.editMaterialList = [];
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.dataList = [];
            $scope.purchaseList = [];

            $scope.orderObj = {
                supplierOrgId: $scope.curOrgId,
                headerInfo: {
                    supplierOrgId: $scope.curOrgId,
                    supplierOrgName: $scope.curOrg.companyName,
                    isStockoutStatistics: 1,
                    forward: 0
                },
                materialList: [],
                bakMaterialsList: []
            };
            $scope.bakList = [];
            $scope.purchaseLevelList = [];
            $scope.deliverStatusList = [{
                    id: 0,
                    name: "未出库"
                },
                {
                    id: 1,
                    name: "部分出库"
                },
                {
                    id: 2,
                    name: "已出库"
                }
            ];
            $scope.deliveryList = [];
            $scope.sellTbConf = {
                fixedWidth: 290,
                scrollWidth: 1380,
                tableCol: [{
                        type: "",
                        name: "意向单号",
                        dataField: "saleNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 200,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购单号",
                        dataField: "purchaseNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "由直投生成",
                        dataField: "isDirectStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购级别",
                        dataField: "purchaseLevelNameShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发运方式",
                        dataField: "deliverTypeNameShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "attach",
                        name: "附件",
                        dataField: "attachName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        clickFn: "downloadAttach",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建方式",
                        dataField: "createTypeShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShows",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货通知状态",
                        dataField: "deliverStatusShow",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "inventoryOutStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "退货申请状态",
                        dataField: "applyReturnShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "CRM单号",
                        dataField: "crmOrder",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "前移单号",
                        dataField: "pmsCode",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 230,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.detailMap = [
                {
                    name: '销售意向单',
                    field: 'saleNo',
                    isShow: true,
                },
                {
                    name: '客户名称',
                    isShow: true,
                    field: 'purchaseOrgName'
                },
                {
                    name: '申请日期',
                    isShow: true,
                    field: 'createDateShow'
                },
                {
                    name: '采购单号',
                    isShow: true,
                    field: 'purchaseNo'
                },
                {
                    name: '采购合同单号',
                    isShow: true,
                    field: 'purchaseContractNo'
                },
                {
                    name: '交货日期',
                    isShow: true,
                    field: 'deliveryDateShow'
                },
                {
                    name: '采购级别',
                    isShow: true,
                    field: 'purchaseLevelNameShow'
                },
                {
                    name: '发运方式',
                    isShow: true,
                    field: 'deliverTypeNameShow'
                },
                {
                    name: '结算方式',
                    isShow: true,
                    field: 'settleTypeName'
                },
                {
                    name: '收货人',
                    isShow: true,
                    field: 'receiverName',
                },
                {
                    name: '联系方式',
                    isShow: true,
                    field: 'receiverPhone',
                },
                {
                    name: '传真',
                    isShow: true,
                    field: 'receiverFax'
                },
                {
                    name: '收货地址',
                    isShow: true,
                    field: 'receiveAddress',
                },
                {
                    name: '订单总价',
                    isShow: true,
                    field: 'totalSettlementPrice'
                },
                {
                    name: '调整总价',
                    isShow: true,
                    field: 'totalDiscountPrice'
                },
                {
                    name: '国家和地区',
                    isShow: true,
                    field: 'country'
                },
                {
                    name: '地区',
                    isShow: true,
                    field: 'region'
                },
                {
                    name: '合同',
                    isShow: true,
                    field: 'contract'
                },
                {
                    name: '机型',
                    isShow: true,
                    field: 'model'
                },
                {
                    name: 'CRM单号',
                    isShow: true,
                    field: 'crmOrder'
                },
                {
                    name: '是否前移',
                    isShow: true,
                    field: 'forward'
                },
                {
                    name: '前移单号',
                    isShow: true,
                    field: 'pmsCode'
                },
                {
                    name: '备注',
                    field: 'remark',
                    isShow: true,
                },
                {
                    name: '尾差金额',
                    field: 'cashShortAndOver',
                    isShow: $scope.isTJ
                }
            ];
            $scope.viewTbConf = {
                scrollWidth: 1980,
                tableCol: [{
                        type: "",
                        name: "序号",
                        dataField: "rownum",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo"
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes"
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit"
                    },
                    {
                        name: "适用机型",
                        width: 100,
                        dataField: "machineModel",
                        input: false,
                    },
                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "qty"
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price"
                    },
                    {
                        name: "申请总价",
                        width: 100,
                        dataField: "applyTotalPrice"
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName"
                    },
                    {
                        name: "调整后数量",
                        width: 100,
                        dataField: "amountAfterAdjust"
                    },
                    {
                        name: "调整后单价",
                        width: 100,
                        dataField: "unitPriceAfterAdjust"
                    },
                    {
                        name: "调整后总价",
                        width: 100,
                        dataField: "totalPriceAfterAdjust"
                    },
                    {
                        name: "标准价",
                        width: 100,
                        dataField: "standardPrice",
                        hidden: !$scope.isJCH, // 仅限基础
                    },
                    {
                        name: "创建发货数量",
                        width: 120,
                        dataField: "informedAmount"
                    },
                    {
                        name: "实际出库数量",
                        width: 120,
                        dataField: "inventoryOutAmount"
                    },
                    {
                        name: "实际库存",
                        width: 100,
                        dataField: "enableNum"
                    },
                    {
                        name: "大厂库存",
                        width: 100,
                        clickFnDaChang: "dachangStock",
                        dataField: "totalStock"
                    },
                    {
                        name: "意向占用",
                        width: 120,
                        dataField: "intentionNum"
                    },
                    {
                        name: "发货占用",
                        width: 120,
                        dataField: "deliveryNum"
                    },
                    {
                        name: "发货时间",
                        width: 150,
                        dataField: "requestDeliveryDateShow"
                    },
                    {
                        name: "备注",
                        width: 150,
                        dataField: "remark"
                    }
                ]
            };
            $scope.deliveryTbConf = {
                scrollWidth: 800,
                tableCol: [{
                        type: "",
                        name: "发货通知单号",
                        dataField: "deliveryNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "结算方式",
                        dataField: "settleTypeName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请日期",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "isOutDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "物流状态",
                        dataField: "logState",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "冲销状态",
                        dataField: "isReverseShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };


            $scope.actionType = 0; // 0: 自动 1:手动、编辑
            $scope.tabFlag = {};
            var tabFlag = {
                0: "手动制定",
                1: "编辑",
                2: "自动制定",
                3: "查看",
                4: "审核",
            };

            $scope.printSingle = function (item) {
                var printList = [];
                var printType = "SaleOrder";
                printList.push({
                    BillId: item.id,
                    BillType: item.billType
                });
                var billState = item.billState === "已完成" ? true : false;
                var param = {
                    billId: printList,
                    printType: printType,
                    billState: billState
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    sellFixedWidth: {
                        left: $scope.sellTbConf.fixedWidth + "px"
                    },
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                $scope.tabFlag.index = index;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        initData();
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    case 5:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.orderObj = {
                    headerInfo: {
                        isStockoutStatistics: 1
                    },
                    materialList: [],
                    bakMaterialsList: []
                };
                $scope.bakList = [];
                $scope.tabFlag = {};
                $scope.editMaterialList = [];
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
                $scope.orderObj.headerInfo.discountPrice = 0;

            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                var service = "device";
                var reqUrl = "/saleIntention/listByUser";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createTypeShow = $filter("CreateWay")(item.createType);
                        item.createDateShow = $filter("YbDate")(item.createDate);
                        item.deliveryDateShow = $filter("YbDate")(item.deliveryDate);
                        item.createDateShows = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.deliverStatusShow = $filter("ProgressStatus")(item.deliverStatus);
                        item.inventoryOutStatusShow = $filter("ProgressStatus")(item.inventoryOutStatus, "outDepot");
                        item.isReturnShow = $filter("ProgressStatus")(item.isReturn, "returnState");
                        item.applyReturnShow = $filter("ProgressStatus")(item.applyReturn, "returnApply");
                        item.isDirectStr = $filter("TrueOrFalse")(item.isDirect);
                        item.purchaseLevelNameShow = item.purchaseTypeChildId ? item.purchaseLevelName + "-" + item.purchaseTypeChildName : item.purchaseLevelName;
                        item.deliverTypeNameShow = item.sendTypeChildId ? item.deliverTypeName + "-" + item.sendTypeChildName : item.deliverTypeName;
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    return resp.value.list
                });
            }

            $scope.toSort = function () {};

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    case "alterReport":
                        alterReport(item);
                        break;
                    case "downloadAttach":
                        downloadAttach(item);
                        break;
                    case "dachangStock":
                        // 大厂库存点击事件
                        dachangStock(item);
                        break;
                    default:
                        break;
                }
            };

            function downloadAttach(item) {
                window.location.href = ybHttp.RequestUrl("device", "/saleIntention/downloadAttach") + '?billId=' + item.id;
            }

            function alterReport(item) {
                var param = {
                    materialsNo: item.materialsNo
                };
                ybWidget.StorageReport(param);
            }

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.switchDatePicker = function (index) {
                $scope.datePickerFlag = [false, false, false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            function getPurchaseDetail(billId) {
                var service = "device";
                var reqUrl = "/purchaseRequest/item";
                var param = {
                    billId: billId
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.orderObj.headerInfo.createDate = new Date();
                    $scope.orderObj.headerInfo.deliveryDate = resp.value.deliveryDate;
                    $scope.orderObj.headerInfo.createType = 0;
                    $scope.orderObj.headerInfo.purchaseNo = resp.value.billNo;
                    $scope.orderObj.headerInfo.purchaseContractNo = resp.value.purchaseContractNo;
                    $scope.orderObj.headerInfo.purchaseOrgId = resp.value.purchaseOrgId;
                    $scope.orderObj.headerInfo.purchaseOrgName = resp.value.purchaseOrgName;
                    $scope.orderObj.headerInfo.supplierOrgId = resp.value.supplierOrgId;
                    $scope.orderObj.headerInfo.supplierOrgName = resp.value.supplierOrgName;
                    $scope.orderObj.headerInfo.purchaseLevelId = resp.value.purchaseType;
                    $scope.orderObj.headerInfo.purchaseLevelNameShow = resp.value.purchaseTypeChildId ? resp.value.typeDesc + "-" + resp.value.purchaseTypeChildName : resp.value.typeDesc;
                    $scope.orderObj.headerInfo.purchaseLevelName = resp.value.typeDesc;
                    $scope.orderObj.headerInfo.purchaseTypeChildId = resp.value.purchaseTypeChildId;
                    $scope.orderObj.headerInfo.purchaseTypeChildName = resp.value.purchaseTypeChildName;
                    $scope.orderObj.headerInfo.deliverTypeName = resp.value.shippingMethod;
                    $scope.orderObj.headerInfo.receiverName = resp.value.receiverName;
                    $scope.orderObj.headerInfo.receiverFax = resp.value.receiverFax;
                    $scope.orderObj.headerInfo.receiverPhone = resp.value.receiverTel;
                    $scope.orderObj.headerInfo.receiveAddress = resp.value.receiverAddress;
                    $scope.orderObj.headerInfo.addressCode = resp.value.addressCode;
                    $scope.orderObj.headerInfo.totalSettlementPrice = resp.value.totalValue;
                    $scope.orderObj.headerInfo.country = resp.value.country;
                    $scope.orderObj.headerInfo.remark = resp.value.remark;
                    $scope.orderObj.headerInfo.isImprove = resp.value.isImprove;
                    $scope.orderObj.headerInfo.isUrgentPrice = resp.value.isUrgentPrice;
                    $scope.orderObj.headerInfo.region = resp.value.region;
                    $scope.orderObj.headerInfo.contract = resp.value.contract;
                    $scope.orderObj.headerInfo.model = resp.value.model;
                    $scope.orderObj.headerInfo.sendTypeChildId = resp.value.sendTypeChildId;
                    $scope.orderObj.headerInfo.sendTypeChildName = resp.value.sendTypeChildName;
                    $scope.orderObj.headerInfo.deliverTypeId = resp.value.shippingMethodId;
                    $scope.orderObj.headerInfo.deliverTypeName = resp.value.shippingMethod;
                    $scope.orderObj.headerInfo.forward =resp.value.forward;
                    angular.forEach(resp.value.materialsList, function (item) {
                        item.isNeedRaise = isNeedRaise($scope.orderObj.headerInfo, item);
                        item.amountAfterAdjust = item.qty;
                        item.requestDeliveryDate = new Date();
                        if (!!item.priceSchemeName) {
                            item.unitPriceAfterAdjust = item.settlementPrice;
                            item.totalPriceAfterAdjust = item.settlementPrice * item.amountAfterAdjust;
                        } else {
                            item.unitPriceAfterAdjust = item.price;
                            item.totalPriceAfterAdjust = item.applyTotalPrice;
                        }
                        if (item.isRaise) {
                            item.isChecked = true;
                            item.unitPriceAfterAdjust = $filter("decimalCover")(raisePrice(item.unitPriceAfterAdjust), 2);
                            item.totalPriceAfterAdjust = $filter("decimalCover")(ybWidget.Times(item.unitPriceAfterAdjust, item.amountAfterAdjust), 2);
                        }
                        pickingBillMaterialChange(item)
                    });
                    $scope.orderObj.materialList = resp.value.materialsList;
                    setTotalPriceAdjust();
                });
            }


            function isNeedRaise(headerInfo, material) {
                return !!material.isRaise;
            }

            function raisePrice(price) {
                return ybWidget.Times(price, 1.05);
            }

            function getPurchaseLevel() {
                var service = "device";
                var reqUrl = "/dataDictionary/searchList";
                var param = {
                    parentCode: "CGJB"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.purchaseLevelList = resp.value;
                })
            }


            $scope.selMateriel = function (e) {
                if (!$scope.orderObj.headerInfo.purchaseOrgName) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                if (!$scope.orderObj.headerInfo.purchaseOrgId) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/saleIntention/download",
                    importReqService: "device",
                    importReqUrl: "/saleIntention/import",
                    importErrorUrl: "",
                    dealerOrgId: $scope.orderObj.headerInfo.purchaseOrgId
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                        item.totalPriceAfterAdjust = $filter("decimalCover")(ybWidget.Times(item.amountAfterAdjust, item.unitPriceAfterAdjust), 2);
                        pickingBillMaterialChange(item)
                    });
                    $scope.orderObj.materialList = [];
                    $scope.orderObj.materialList = angular.copy(data);
                    setTotalPrice();
                    setTotalPriceAdjust();
                });
            };

            $scope.adjustDelMateriel = function (index, e) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.materialList.splice(index, 1);
                    e.stopPropagation();
                });
            };

            $scope.delMateriel = function (item, index, e) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.materialList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                    setTotalPriceAdjust();
                    e.stopPropagation();
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.materialList.length; i < len; i++) {
                    if (!!$scope.orderObj.materialList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.materialList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.materialList[i].isChecked) {
                            $scope.orderObj.materialList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.materialList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            function setPrice(item, colItem) {
                item.qtyErr = false;
                if (!item[colItem] || parseFloat(item[colItem]) <= 0) {
                    item.qtyErr = true;
                    return;
                }
                if (item.qty > 99999999.99) {
                    item.qty = 99999999.99;
                }
                item.amountAfterAdjust = item.qty;
                if (angular.isUndefined(item[colItem]) || item[colItem] === "") {
                    item.applyTotalPrice = "";
                } else {
                    item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.price), 2);
                }
                setTotalPrice();
                if (!!item.unitPriceAfterAdjust) {
                    if (item.amountAfterAdjust === "" || !item.unitPriceAfterAdjust) {
                        item.totalPriceAfterAdjust = ""
                    } else {
                        item.totalPriceAfterAdjust = $filter("decimalCover")(ybWidget.Times(item.amountAfterAdjust, item.unitPriceAfterAdjust), 2);
                    }
                    setTotalPriceAdjust();
                }
            }


            function setTotalPrice() {
                var totalPrice = 0;
                angular.forEach($scope.orderObj.materialList, function (item) {
                    if (!item.applyTotalPrice) {
                        return false;
                    }
                    totalPrice = ybWidget.Plus(totalPrice, parseFloat(item.applyTotalPrice));
                });
                $scope.orderObj.headerInfo.totalSettlementPrice = $filter("decimalCover")(totalPrice, 2);
            }

            function setTotalPriceAdjust() {
                var totalPrice = 0;
                angular.forEach($scope.orderObj.materialList, function (item) {
                    if (!item.totalPriceAfterAdjust) {
                        return false;
                    }
                    totalPrice = ybWidget.Plus(totalPrice, parseFloat(item.totalPriceAfterAdjust));
                });
                $scope.orderObj.headerInfo.totalDiscountPrice = $filter("decimalCover")(totalPrice, 2);
            }


            $scope.switchListDatePicker = function (item) {
                angular.forEach($scope.orderObj.materialList, function (item) {
                    item.showDatePicker = false;
                });
                item.showDatePicker = true;
            };

            EventBus.Subscribe("onMaterialChange", setTotal);

            function setTotal() {
                setTotalPrice();
                setTotalPriceAdjust();
            }

            $scope.$on("$destroy", function () {
                EventBus.Unsubscribe("onMaterialChange", setTotal);
            });
            function getDetail(saleIntentionId) {
                var service = "device";
                var reqUrl = "/saleIntention/item";
                var param = {};
                param.id = saleIntentionId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.value, MESG_TYPE.Error);
                        return false;
                    }
                    angular.forEach(resp.value.materialList, function (item) {
                        item.requestDeliveryDate = new Date(item.requestDeliveryDate);
                    });
                    return resp.value;
                });
            }
            function viewDetail(item, isCheckFlag) {
                $scope.isCheckFlag = isCheckFlag
                $scope.tabFlag.name = isCheckFlag ? tabFlag[4] : tabFlag[3]
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.subTabFlag = [true, false];
                    $scope.changeTab(4);
                    data.headerInfo.deliverTypeNameShow = data.headerInfo.sendTypeChildId ? data.headerInfo.deliverTypeName + "-" + data.headerInfo.sendTypeChildName : data.headerInfo.deliverTypeName;
                    data.headerInfo.purchaseLevelNameShow = data.headerInfo.purchaseTypeChildId ? data.headerInfo.purchaseLevelName + "-" + data.headerInfo.purchaseTypeChildName : data.headerInfo.purchaseLevelName;
                    $scope.orderObj = data;
                    $scope.orderObj.headerInfo.createDateShow = $filter("YbDate")($scope.orderObj.headerInfo.createDate)
                    $scope.orderObj.headerInfo.deliveryDateShow = $filter("YbDate")($scope.orderObj.headerInfo.deliveryDate)
                    angular.forEach($scope.orderObj.materialList, function (item) {
                        item.requestDeliveryDateShow = $filter("YbDate")(item.requestDeliveryDate);
                        pickingBillMaterialChange(item)
                    });
                });
            }

            $scope.getDeliveryNotice = function () {
                var service = "device";
                var reqUrl = "/deliveryNote/list";
                var param = {};
                param.pageNum = 0;
                param.pageSize = 0;
                param.filters = {
                    saleNo: $scope.orderObj.headerInfo.saleNo
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isReverseShow = $filter("ProgressStatus")(item.isReverse, "reverse");
                        item.createDateShow = $filter("YbDate")(item.createDate);
                        item.deliveryDateShow = $filter("YbDate")(item.deliveryDate)
                    });
                    $scope.deliveryList = resp.value.list;
                });
            };



            /**
             * ***************************************** 大厂库存  开始 *****************************************
             */


            $scope.sapStockMap = {}

            // 处理手动制定销售意向
            EventBus.Subscribe("onMaterialSelect", pickingBillMaterialChange);

            function pickingBillMaterialChange(item) {
                // 处理大厂库存逻辑
                // 仅限基础、能源
                if (!$scope.isJCH && !$scope.isNY) return
                var service = 'device';
                var reqUrl = '/materialsSchedule/sapStock';
                var param = {
                    materialsNo: item.materialsNo
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.sapStockMap[item.materialsNo] = resp.value || {}
                });
            }

            function dachangStock(item) {
                var param = {
                    title: '大厂库存',
                    data: item.detailVOList || []
                };
                ybWidget.DatasShow(param);
            }


            /**
             * ***************************************** 大厂库存  结束 *****************************************
             */

            (function () {
                var sellIntentionBillNo = window.sessionStorage.getItem("sellIntentionBillNo");
                window.sessionStorage.removeItem("sellIntentionBillNo");
                if (!!sellIntentionBillNo) {
                    $scope.condition.saleNo = sellIntentionBillNo;
                    getDataList().then(function (data) {
                        viewDetail(data[0]);
                    })
                } else {
                    getDataList();
                }


                getPurchaseLevel();
                $scope.setFixedWidth();
            })();
        }]);
})(window, window.angular);